import classnames from 'classnames';
import { useDrag } from 'react-dnd';
import { DragElementLayout } from './DragDropStyle';

type IDataObj = {
  data: any;
  [key: string]: any;
};

interface Props {
  item: IDataObj;
  type?: string;
  onClick?: () => void;
  onDoubleClick?: () => void;
  endDrag?: (draggedItem: IDataObj) => void;
  isBlock?: boolean;
  className?: string;
  style?: React.CSSProperties;
  children?: React.ReactNode;
}

export const DragElement: React.FC<Props> = (props) => {
  const {
    item,
    type = 'Box',
    onClick = () => {},
    onDoubleClick,
    endDrag,
    isBlock,
    className,
    style,
    children,
  } = props;

  const [{ isDragging }, dragRef] = useDrag({
    type,
    item,
    collect: (monitor) => ({
      isDragging: !!monitor.isDragging(),
    }),
    end: (draggedItem, monitor) => {
      if (!monitor.didDrop()) {
        return;
      }

      if (endDrag) {
        endDrag(draggedItem);
      }
    },
  });

  return (
    <DragElementLayout
      ref={dragRef}
      onClick={onClick}
      onDoubleClick={onDoubleClick}
      className={classnames('dragElement', className, {
        ['is-block']: isBlock,
        ['is-dragging']: isDragging,
      })}
      style={style}>
      {children}
    </DragElementLayout>
  );
};
